package test.orther;

import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import test.dto.FileUploadRequestDTO;
import test.utils.FilePathUtil;
import test.utils.FileUtil;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/6/8 17:41
 * @ Description:
 */
@Slf4j
@Service
public class RandomAccessUploadStrategy extends SliceUploadTemplate {

    @Autowired
    private FilePathUtil filePathUtil;

    @Value("${upload.chunkSize}")
    private long defaultChunkSize;

    @Override
    public boolean upload(FileUploadRequestDTO param) throws Exception {
        RandomAccessFile accessTmpFile = null;
        try {
            //获取文件所在文件夹路径
            String uploadDirPath = filePathUtil.getPath(param);
            //创建临时文件
            File tmpFile = super.createTmpFile(param);
            //创建随机读取文件
            accessTmpFile = new RandomAccessFile(tmpFile, "rw");
            //这个必须与前端设定的值一致
            long chunkSize = Objects.isNull(param.getChunkSize()) ? defaultChunkSize * 1024 * 1024
                    : param.getChunkSize();
            //分片大小*分片序号=偏移量
            long offset = chunkSize * param.getChunk();
            //定位到该分片的偏移量
            accessTmpFile.seek(offset);
            //把前端传过来的分片数据写入对应位置
            accessTmpFile.write(param.getFile().getBytes());
            //检查该片是否全部写入
            boolean isOk = super.checkAndSetUploadProgress(param, uploadDirPath);
            return isOk;
        } catch (IOException e) {
            //log.error(e.getMessage(), e);
        } finally {
            FileUtil.close(accessTmpFile);
        }
        return false;
    }

}
